package com.cbg.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cbg.base.constant.Constant;
import com.cbg.bus.entity.Order;
import com.cbg.bus.entity.Rider;
import com.cbg.bus.entity.Ticket;
import com.cbg.bus.service.IRiderService;
import com.cbg.dg.service.IPassengerService;
import com.cbg.discount.service.IDiscountService;
import com.cbg.sys.entity.HistoryRoute;
import com.cbg.sys.entity.LineCar;
import com.cbg.sys.entity.Route;
import com.cbg.sys.entity.SeatPrice;
import com.cbg.sys.mapper.LineMapper;
import com.cbg.sys.mapper.SeatPriceMapper;
import com.cbg.sys.service.ILineCarService;
import com.cbg.sys.service.IRouteService;
import com.cbg.sys.service.ISeatPriceService;
import com.cbg.base.core.SuperServiceImpl;
import com.cbg.sys.utils.PriceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 座位价格表 服务实现类
 * </p>
 *
 * @author chenbing
 * @since 2018-12-18
 */
@Service
public class SeatPriceServiceImpl extends SuperServiceImpl<SeatPriceMapper, SeatPrice> implements ISeatPriceService {
    @Autowired
    IPassengerService passengerService;
    @Autowired
    IRiderService riderService;
    @Autowired
    IRouteService routeService;
    @Autowired
    LineMapper lineMapper;
    @Autowired
    ILineCarService lineCarService;
    @Autowired
    IDiscountService discountService;

    /**
     * 后期MQ处理
     */
    @Override
    @Transactional
    public boolean bookSeat(String userId, String lineId, String typeId,List<String> riderIds,List<Integer> seatIds,String contactName,
        String contactTel,String rideAddress, String debusAddress,String discountId,String outTradeNo) {
        try {
            //处理座位
            LineCar lineCar = lineCarService.getOne(new LambdaQueryWrapper<LineCar>()
                    .eq(LineCar::getLineId, lineId).eq(LineCar::getTypeId, typeId));
            Integer status = lineCar.getStatus();
            for (Integer seatId:seatIds){
                status+=(int) Math.pow(2,seatId);
            }
            lineCar.setStatus(status);
            lineCarService.updateById(lineCar);

            //更新紧急联系人
            passengerService.getById(userId).setContactName(contactName).setContactTel(contactTel).updateById();

            //添加历史路线
            Route route = lineMapper.routeByLineId(lineId);
            new HistoryRoute(userId,route.getId()).insert();

            //创建Ticket
            List<Rider> riders = riderService.list(new LambdaQueryWrapper<Rider>().in(Rider::getId, riderIds));
            Ticket ticket = new Ticket(route.getOrigin(),route.getDestination(),route.getOrigin()+"-"+route.getDestination(),
                    StrUtil.join(",",riders.stream().map(Rider::getName)
                            .collect(Collectors.toList())),StrUtil.join(",", riders.stream().map(Rider::getTel)
                    .collect(Collectors.toList())),StrUtil.join(",",seatIds),rideAddress,debusAddress);
            ticket.insert();

            //根据优惠券、座位价格详情，计算订单总价
            BigDecimal toDeduct=new BigDecimal(0);
            if (Objects.nonNull(discountId))
                toDeduct = discountService.getById(discountId).getAmountMoney();
            SeatPrice seatPrice = PriceUtils.esurePriceByLineId(lineId, typeId);
            BigDecimal total = seatIds.stream().map(x -> PriceUtils.esurePriceBySeatId(x, seatPrice)).reduce(new BigDecimal(0), BigDecimal::add);
            Order order = new Order(outTradeNo,Constant.NOT_PAY,total.subtract(toDeduct),ticket.getId());
            order.insert();
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
